package com.leonzx.base.controller.layim;

import com.leonzx.base.config.pager.Page;
import com.leonzx.base.config.pager.PageInfo;
import com.leonzx.base.constants.IMConstants;
import com.leonzx.base.controller.base.BaseController;
import com.leonzx.base.entity.system.ChatBody;
import com.leonzx.base.service.system.ChatBodyService;
import com.leonzx.base.service.system.OrdersService;
import com.leonzx.base.service.system.UserService;
import com.leonzx.base.utils.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author:李晓雷
 * @Description:
 * @Date: 18/07/30 10:32
 */
@RestController
@RequestMapping("/ajax/layim")
public class AjaxLayImController extends BaseController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private ChatBodyService chatBodyService;
    @Autowired
    private UserService userService;

    /**
     * 遵守LayIm上传图片接口规定
     * 该接口所返回的信息（response）应该严格按照下述的JSON格式：
     * "code": 0 //0表示成功，其它表示失败
     * ,"msg": "" //失败信息
     * ,"data": {
     * "src": "http://cdn.xxx.com/upload/images/a.jpg" //图片url
     * }
     *
     * @param number
     * @param file
     * @return
     */

    @RequestMapping("/uploadImg")
    public Map<String, Object> uploadImg(String number, MultipartFile file, HttpServletRequest request) {
        Map<String, Object> result = getMap();
        try {
            result = ordersService.uploadImg(number, file, request);
            result.put("code", "0");
            result.put("msg", "上传图片成功");
        } catch (Exception e) {
            logger.error("上传图片失败 " + number + "", e);
            result.put("code", "1");
            result.put("msg", "上传图片失败");
        }
        return result;
    }

    @RequestMapping("/uploadFile")
    public Map<String, Object> uploadFile(String number, MultipartFile file, HttpServletRequest request) {
        Map<String, Object> result = getMap();
        try {
            result = ordersService.uploadFile(number, file, request);
            result.put("code", "0");
            result.put("msg", "上传文件成功");
        } catch (Exception e) {
            logger.error("上传图片失败 " + number + "", e);
            result.put("code", "1");
            result.put("msg", "上传文件失败");
        }
        return result;
    }

    @RequestMapping("/historyMessage")
    public Map<String, Object> getHistoryMessage(ChatBody chatBody, String mobile, @PageInfo(pageSize = Page.PAGE_SIZE, orderBy = "createTime") Page<ChatBody> page, HttpServletRequest request) {
        Map<String, Object> result = getMap();
        try {
            String receiveId = request.getParameter("id");
            String type = request.getParameter("type");

            String fromId;
            if (StringUtils.isBlank(mobile)) {
                fromId = currentUser().getId();
                result = getMessage(fromId, receiveId, type, page);
            } else {
                fromId = chatBody.getFrom_id();
                receiveId = chatBody.getId();
                result = getMobileMessage(fromId, receiveId, type, page);
            }
        } catch (Exception e) {
            logger.error("获取聊天信息失败", e);
            addFailMessage(result, "获取聊天信息失败");
        }
        return result;
    }


    @RequestMapping("/changeImUserStatus")
    public Map<String, Object> changeImUserStatus(String userId, String status) {
        Map<String, Object> result = getMap();
        try {
            userService.changeImStatusById(status, userId);
        } catch (Exception e) {
            logger.error("改变IM登录状态失败", e);
            addFailMessage(result, "改变IM登录状态失败");
        }
        return result;
    }

    @RequestMapping("/changeImUserSign")
    public Map<String, Object> changeImUserSign(String userId, String value) {
        Map<String, Object> result = getMap();
        try {
            userService.changeImSignById(value, userId);
        } catch (Exception e) {
            logger.error("改变IM登录状态失败", e);
            addFailMessage(result, "改变IM登录状态失败");
        }
        return result;
    }

    private Map<String, Object> getMessage(String fromId, String toId, String type, Page<ChatBody> page) {
        Map<String, Object> result = getMap();
        ChatBody chatBody = new ChatBody();
        List<ChatBody> chatBodyList;
        if (Objects.equals(IMConstants.LAYIM_TYPE_FRIEND, type)) {
            chatBody.setTo_id(toId);
            chatBody.setFrom_id(fromId);
            chatBodyList = chatBodyService.getFriendDataByFromIdAndToId(chatBody);
        } else {
            chatBody.setGroup_id(toId);
            chatBodyList = chatBodyService.getGroupDataByGroupId(chatBody);
        }
        page.setResult(chatBodyList);
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");

        //循环list，处理数据
        for (ChatBody b : chatBodyList) {
            String createTimeStr = "";
            if (b.getCreateTime() != null) {
                createTimeStr = sdf.format(b.getCreateTime());
            }
            String createUserName = userService.getUserNameById(b.getCreateUserId());
            b.setCreateUserName(createUserName);
            b.setCreateTimeStr(createTimeStr);
            b.setLandUserId(fromId);
            b.setAvatar("/static/im/images/user.png");
        }
        result.put("page", page);
        result.put("data", chatBodyList);
        result.put("code", "0");
        result.put("msg", "加载完成");
        return result;
    }

    private Map<String, Object> getMobileMessage(String fromId, String toId, String type, Page<ChatBody> page) {
        Map<String, Object> result = getMap();
        ChatBody chatBody = new ChatBody();
        List<ChatBody> chatBodyList;
        if (Objects.equals(IMConstants.LAYIM_TYPE_FRIEND, type)) {
            chatBody.setFrom_id(fromId);
            chatBody.setTo_id(toId);
            chatBodyList = chatBodyService.getFriendDataByFromIdAndToId(chatBody);
        } else {
            chatBody.setGroup_id(toId);
            chatBodyList = chatBodyService.getGroupDataByGroupId(chatBody);
        }
        page.setResult(chatBodyList);
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");

        //排序
        Collections.sort(chatBodyList, (o1, o2) -> (int) (o2.getCreateTime().getTime() - o1.getCreateTime().getTime()));

        //循环list，处理数据
        for (ChatBody b : chatBodyList) {
            String createTimeStr = "";
            if (b.getCreateTime() != null) {
                createTimeStr = sdf.format(b.getCreateTime());
            }
            String createUserName = userService.getUserNameById(b.getCreateUserId());
            b.setCreateTimeStr(createTimeStr);
            b.setCreateUserName(createUserName);
            b.setLandUserId(fromId);
            b.setAvatar("/static/im/images/user.png");
        }
        result.put("page", page);
        result.put("data", chatBodyList);
        result.put("code", "1");
        result.put("msg", "加载完成");
        result.put("totalPages", page.getTotalPages());
        return result;
    }
}
